package com.sfx.concurrent.demo.concurrent.AtomicTest.demo2;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-18
 * Time: 19:01
 */
public class AccountAtomicReference implements DecimalAccount{
    private AtomicReference<BigDecimal> atomicReference;

    public AccountAtomicReference(BigDecimal balance) {
        this.atomicReference = new AtomicReference<>(balance);
    }


    public BigDecimal getBalance() {
        return atomicReference.get();
    }

    @Override
    public void withDraw(BigDecimal money) {
        while(true) {
            BigDecimal prev = atomicReference.get();//获取旧值(希望的值)
            BigDecimal next = prev.subtract(money);
            if(atomicReference.compareAndSet(prev,next)){
                break;
            }
        }
    }

    public static void main(String[] args) {
        AccountAtomicReference atomicReference =
                new AccountAtomicReference(new BigDecimal("10000"));
        DecimalAccount.demo(atomicReference);
    }

}
